/*
 * main.c
 * Project 03
 * Nicole Ang (nang1@asu.edu)
 * Bijan Fakhri (bfakhri@asu.edu)
 * CSE325 Embedded Microprocessor Systems
 * Spring 2013
 */

#include "support_common.h" /* include peripheral declarations and more */
#include "uc_dipsw.h"
#include "uc_led.h"
#include "dtim.h"
#include "gpio.h"

/* Polls DIP switches 3 and 4 to see what the delay should be set to.
 * Returns the delay in ms. */
static int dipsw_delay_poll(){
	//get signal of switches
	int state3 = uc_dipsw_get_state(3);
	int state4 = uc_dipsw_get_state(4);
	
	int state = (state3 << 1) | state4; //10 | 1 = 11
	int delay = 0;
	switch(state){ // 0 = on, 1 = off
	case 1: delay = 450; //01 = s3 on, s4 off
	break;
	case 2: delay = 350; //10 = s3 off, s4 on
	break;
	case 3: delay = 250; //11 = s3 off, s4 off
	break;
	default: delay = 550; //00 = s3 on, s4 on
	break;
	}
	return delay;
}

/* Polls DIP switch 2 to see if the program should be reversed because it has
 * been moved to the Off position or if the program should go back to its 
 * original direction because it has been moved to the On position. */
static int dipsw_onoff_poll(){
	return gpio_port_dd_get_pin_state(2);
}

/* Flash the LED's in the proper sequence per the project requirements. */
static void flash_led_sequence(int p_delay){
	//poll switch 3 & 4 to determine if delay changes
	p_delay = dipsw_delay_poll();

	//poll switch 2 to see if sequence should be switched
	int state2 = dipsw_onoff_poll();
	
	if(state2){//switch 2 is off, reverse direction 
		for(int i = 4; i > 0; i--){
			uc_led_on(i);
			dtim0_delay(p_delay);
			uc_led_off(i);
			dtim0_delay(p_delay);
		}
	} else{ //switch is on, original direction
		for(int i = 1; i < 5; i++){
			uc_led_on(i);
			dtim0_delay(p_delay);
			uc_led_off(i);
			dtim0_delay(p_delay);
		}
	}
}

/* Calls uc_dispw_init() to initialize the DIP switch.
 * uc_led_init() to initialize the LED's
 * dtim0_init() to initialize DTIM0 */
static void init(){
	uc_dipsw_init();
	uc_led_init();
	dtim0_init();
}

/* Calls init() to initialize the hardware. Then drops into an infinite loop
 * calling flash_led_sequence() forever. */
int main(){
	init();
	int delay = 250; //initially delay is 250 ms
	
	//make sure all LEDS are off initially
	uc_led_all_off();
	
	while(1){
		flash_led_sequence(delay);
	}
	return 0;
}
